package com.handu.luna.core.domain.promotion;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Transient;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.validation.constraints.Min;

import org.springframework.data.jpa.domain.Specification;

import com.handu.luna.core.domain.goods.Goods;

@Entity
public class SalesPromotionGoods extends Promotion {
	
	private long salesPromotionId;
	
	private long goodsId;
	
	@Transient
	private Goods goods;
	
	@Min(value = 0, message = "促销活动商品售价不能低于0")
	private BigDecimal goodsPrice;
	
	public Goods getGoods() {
		if(this.goodsId != 0 && goods == null){
			goods = context.getGoodsRepository().findOne(this.goodsId);
		}
		return goods;
	}

	public void setGoods(Goods goods) {
		this.goods = goods;
	}

    public long getSalesPromotionId() {
        return salesPromotionId;
    }

    public void setSalesPromotionId(long salesPromotionId) {
        this.salesPromotionId = salesPromotionId;
    }

    public void setSalesPromotionId(int salesPromotionId) {
		this.salesPromotionId = salesPromotionId;
	}

	public long getGoodsId() {
		return goodsId;
	}

	public void setGoodsId(long goodsId) {
		this.goodsId = goodsId;
	}

	public BigDecimal getGoodsPrice() {
		return goodsPrice;
	}

	public void setGoodsPrice(BigDecimal goodsPrice) {
		this.goodsPrice = goodsPrice;
	}
	
	public String getSucessFlashMessage(){
		String messagePrefix = (null==this.getId() ?"添加" : "修改");
		try {
			return messagePrefix + this.getGoods().getName() + "成功。";
		} catch ( SecurityException e) {
			return messagePrefix + "成功。";
		}
	}
	
	
	//张恒强添加  查询某些促销活动下的商品
	//未加入考虑当前登陆的会员等级
	public Specification<SalesPromotionGoods> searchPromotioningGoods(List<Long> salesPromotionIds){
		
		return new Specification<SalesPromotionGoods>() {

			@Override
			public Predicate toPredicate(Root<SalesPromotionGoods> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				
				return query.where(root.get("salesPromotionId").in(salesPromotionIds)).getRestriction();
			}
		};
	}

}
